/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 适用于ProTable中的rangePicker
 * 参数见interface
 */

import { useState } from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import type { Moment } from 'moment';
import moment from 'moment';

interface RangeType {
  isUseToady?: boolean; // 是否允许选择今天
  defaultRange?: number; // 默认时间区间
  rangeDays?: number; // 可用时间区间
  limitValueRange?: number; // 最大选择区间
  title?: string;
  dataIndex?: string;
  valuesKeys?: string[]; // 格式化日期的keys
  [name: string]: any;
}

export function useRangePicker(props: RangeType): ProColumns {
  const {
    isUseToady = true,
    defaultRange = 7,
    rangeDays = 365,
    limitValueRange = 30,
    title = '日期',
    dataIndex = 'dates',
    valuesKeys = ['start_time', 'end_time'],
    ...rest
  } = props;
  const [dates, setDates] = useState<Moment[]>();
  // 默认时间
  const defaultDateRange = [
    moment().subtract(defaultRange + (isUseToady ? 0 : 1), 'days'),
    moment().subtract(isUseToady ? 0 : 1, 'days'),
  ];
  // 可选最大区间
  const rangeDate = {
    start: moment(defaultDateRange[1]).subtract(rangeDays, 'days'),
    end: defaultDateRange[1],
  };

  const onOpenChange = (status: boolean): void => {
    if (status) {
      setDates([]);
    }
  };
  const rangePickerDisabled = (current: Moment): boolean => {
    // 是否含在区间内
    const isInRange = current.isBetween(moment(rangeDate.start), moment(rangeDate.end));
    if (!isInRange) return true;
    // 空值比较
    if (!dates || dates.length === 0) {
      return !(current <= defaultDateRange[1]);
    }
    // 日期比较
    const [first, second] = dates;
    const tooLate = first && current.diff(first, 'days') >= limitValueRange;
    const secondRange = !(first && second && second.diff(first, 'days') < limitValueRange);
    const tooEarly =
      second &&
      second.diff(current, 'days') >= (first && secondRange ? rangeDays : limitValueRange);
    return tooEarly || tooLate;
  };

  return {
    title,
    dataIndex,
    hideInTable: true,
    valueType: 'dateRange',
    initialValue: defaultDateRange,
    filters: true,
    search: {
      transform: (value: any) => ({ [valuesKeys[0]]: value[0], [valuesKeys[1]]: value[1] }),
    },
    fieldProps: {
      onCalendarChange: (values: Moment[]) => setDates(values),
      disabledDate: rangePickerDisabled,
      onOpenChange,
      allowClear: false,
    },
    ...rest,
  };
}
